import { Request } from '../models/request.model';
import { Response } from '../models/response.model';

/**
 * HTTP服务类
 * 负责发送HTTP请求并处理响应
 */
export class HttpService {
  /**
   * 发送HTTP请求
   * @param request 请求对象
   * @returns 响应对象Promise
   */
  static async sendRequest(request: Request): Promise<Response> {
    try {
      // 获取URL
      const url = request.getFullUrl();
      if (!url) {
        throw new Error('URL不能为空');
      }

      // 创建请求选项
      const options = request.createRequestOptions();
      
      // 记录开始时间
      const startTime = performance.now();
      
      // 发送请求
      const response = await fetch(url, options);
      
      // 处理响应
      let responseBody: any;
      const contentType = response.headers.get('content-type') || '';
      
      if (contentType.includes('application/json')) {
        responseBody = await response.json();
      } else if (contentType.includes('text/')) {
        responseBody = await response.text();
      } else {
        // 二进制数据
        responseBody = await response.blob();
      }
      
      // 计算响应时间
      const endTime = performance.now();
      const time = Math.round(endTime - startTime);
      
      // 创建响应对象
      return Response.fromFetchResponse(response, responseBody, time);
    } catch (error) {
      console.error('Error sending request:', error);
      
      // 创建错误响应
      return new Response({
        status: 0,
        statusText: error instanceof Error ? error.message : String(error),
        time: 0
      });
    }
  }

  /**
   * 发送多个请求
   * @param requests 请求对象数组
   * @returns 响应对象数组Promise
   */
  static async sendRequests(requests: Request[]): Promise<Response[]> {
    return Promise.all(requests.map(request => this.sendRequest(request)));
  }

  /**
   * 中断所有正在进行的请求
   * 注: 实际上fetch API没有直接提供中断请求的方法，
   * 我们需要使用AbortController，这个方法仅为接口示意
   */
  static abortAllRequests(): void {
    console.warn('abortAllRequests is not implemented');
  }
} 